package com.woniu113.junk.user.controller;

import cn.hutool.core.bean.BeanUtil;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu113.junk.commons.model.Result;
import com.woniu113.junk.commons.util.RedisUtil;
import com.woniu113.junk.commons.util.TokenUtil;
import com.woniu113.junk.user.Param.AccountLogParam;
import com.woniu113.junk.user.Param.adminInfo.*;
import com.woniu113.junk.user.controller.form.AccountLogForm;
import com.woniu113.junk.user.controller.form.adminInfo.*;
import com.woniu113.junk.user.dto.AdminInfoDto;
import com.woniu113.junk.user.dto.FindSuitableRiderDTO;
import com.woniu113.junk.user.dto.adminInfo.AllAdminInfoDto;
import com.woniu113.junk.user.dto.adminInfo.FindAdminDTO;
import com.woniu113.junk.user.dto.adminInfo.findByStationIdDTO;
import com.woniu113.junk.user.exception.UserException;
import com.woniu113.junk.user.model.AdminInfo;
import com.woniu113.junk.user.service.AdminInfoService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 蜡笔没了小新
 * @since 2024年10月19日
 */
@RestController
@RequestMapping("/adminInfo")
public class AdminInfoController {
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private AdminInfoService adminInfoService;
    @PostMapping("/adminLog")
    @ApiOperation("管理员登录")
    public Result<AdminInfo> adminLog(@RequestBody AccountLogForm form , HttpServletResponse response, HttpServletRequest request) throws Exception {
        System.out.println("账号"+form.getUserName());
        System.out.println("密码"+form.getPassword());

        AdminInfo adminInfo =adminInfoService.adminLog(BeanUtil.toBean(form, AccountLogParam.class));
        //签发jwt(令牌)(会话跟踪)
        HashMap<String, Object> map = new HashMap<>();//键值对(存入用户信息)
        map.put("userId",adminInfo.getAdminId());
        String accessToken = TokenUtil.createToken(map, 60);//传入键值对和有效期(1分钟)
        String refreshToken = TokenUtil.createToken(map, 24 * 60);//长token,保存在redis中(有效期为1天)
        System.out.println("accessToken1"+accessToken);
        System.out.println("refreshToken1"+refreshToken);
        //以短token为键,以长token为值,将长token存到redis中,同时设置过期时间保持与长token一致(设置的是以秒为单位的)
        redisUtil.set(accessToken,refreshToken,24*60*60);
        System.out.println("redisUtil.get(accessToken):"+redisUtil.get(accessToken));
        //设置响应头,通过响应头将jwt响应给客户端(前端)
        response.setHeader("token", accessToken);//响应头的名字,令牌(通过双token机制响应给用户的为短token)
        //在跨域请求访问时 必须公开该请求头 前端才能获取到
        response.setHeader("Access-Control-Expose-Headers","token");
        return Result.getResult(AdminInfo.class).setData(adminInfo).setCode(200);
    }

    @GetMapping("/sendLoginCode")
    @ApiOperation("发送登录验证码")
    public Result sendLoginCode(@RequestParam String phoneNumber) throws Exception {
        System.out.println("电话"+phoneNumber);

        adminInfoService.sendLoginCode(phoneNumber);
        return Result.getResult().setMsg("发送成功").setCode(200);
    }
    @PostMapping("/adminCodeLogin")
    @ApiOperation("用户手机号登录")
    public Result<AdminInfo> adminCodeLogin(@RequestBody AdminCodeLoginForm form, HttpServletResponse response) throws Exception {
        System.out.println("电话"+form.getUserPhone());
        System.out.println("验证码"+form.getCode());

        AdminInfo adminInfo =adminInfoService.adminCodeLogin(BeanUtil.toBean(form, AdminCodeLoginParam.class));
        //签发jwt(令牌)(会话跟踪)
        HashMap<String, Object> map = new HashMap<>();//键值对(存入用户信息)
        map.put("userId",adminInfo.getAdminId());
        String accessToken = TokenUtil.createToken(map, 60);//传入键值对和有效期(1分钟)
        String refreshToken = TokenUtil.createToken(map, 24 * 60);//长token,保存在redis中(有效期为1天)
//        System.out.println("accessToken1"+accessToken);
//        System.out.println("refreshToken1"+refreshToken);
        //以短token为键,以长token为值,将长token存到redis中,同时设置过期时间保持与长token一致(设置的是以秒为单位的)
        redisUtil.set(accessToken,refreshToken,24*60*60);
//        System.out.println("redisUtil.get(accessToken):"+redisUtil.get(accessToken));
        //设置响应头,通过响应头将jwt响应给客户端(前端)
        response.setHeader("token", accessToken);//响应头的名字,令牌(通过双token机制响应给用户的为短token)
        //在跨域请求访问时 必须公开该请求头 前端才能获取到
        response.setHeader("Access-Control-Expose-Headers","token");
        return Result.getResult(AdminInfo.class).setData(adminInfo);
    }




    @GetMapping("/disableAccount")
    @ApiOperation("禁用账号")
    public Result disableAccount(@RequestParam Integer adminId) {
        adminInfoService.disableAccount(adminId);
        return Result.getResult().setMsg("禁用账号成功").setCode(200);
    }
    @GetMapping("/enableAccount")
    @ApiOperation("启用账号")
    public Result enableAccount(@RequestParam Integer adminId) {
        adminInfoService.enableAccount(adminId);
        return Result.getResult().setMsg("启用账号成功").setCode(200);
    }
    @GetMapping("/deleteAccount")
    @ApiOperation("删除账号")
    public Result deleteAccount(@RequestParam Integer adminId) {
        adminInfoService.deleteAccount(adminId);
        return Result.getResult().setMsg("删除账号成功").setCode(200);
    }
    @GetMapping("/selectAdminById")
    @ApiOperation("根据id查询管理员信息")
    public Result<AdminInfo> selectAdminById(@RequestParam Integer adminId) {
        AdminInfo adminInfo = adminInfoService.getById(adminId);
        if (adminInfo==null)throw new UserException("管理员不存在",2001);
        return Result.getResult(AdminInfo.class).setData(adminInfo).setCode(200);
    }
    @PostMapping("/addAdmin")
    @ApiOperation("添加管理员")
    public Result addAdmin(@RequestBody AddAdminForm form) throws Exception {
        System.out.println("账号"+form.getAdminName());
        System.out.println(form.getPassword());
        System.out.println(form.getAdminPhone());
        System.out.println(form.getRealName());
        System.out.println(form.getRoleId());
        System.out.println("站点id"+form.getStationId());
        AddAdminParam param = BeanUtil.toBean(form, AddAdminParam.class);
        adminInfoService.addAdmin(param);
        return Result.getResult().setMsg("添加管理员成功").setCode(200);
    }
    @GetMapping("/userCheckOldPassword")
    @ApiOperation("管理员校验旧密码")
    public Result userCheckOldPassword(@RequestParam String Password,@RequestHeader String token) throws Exception {
        int userId = Integer.parseInt(TokenUtil.parseToken(redisUtil.get(token)).get("userId").toString());
        AdminPasswordParam param = new AdminPasswordParam();
        param.setUserId(userId);
        param.setPassword(Password);
        adminInfoService.userCheckOldPassword(param);
        return Result.getResult().setMsg("校验旧密码成功").setCode(200);
    }
    @GetMapping("/userUpdatePassword")
    @ApiOperation("管理员修改密码")
    public Result userUpdatePassword(@RequestParam String Password,@RequestHeader String token) throws Exception {
        int userId = Integer.parseInt(TokenUtil.parseToken(redisUtil.get(token)).get("userId").toString());
        AdminPasswordParam param = new AdminPasswordParam();
        param.setUserId(userId);
        param.setPassword(Password);
        adminInfoService.userUpdatePassword(param);
        return Result.getResult().setMsg("修改密码成功").setCode(200);
    }
    @PostMapping("/assignRoles")
    @ApiOperation("分配角色")
    public Result assignRoles(@RequestBody AdminAssignRolesForm form) throws Exception {
        adminInfoService.assignRoles(BeanUtil.toBean(form, AdminAssignRolesParam.class));
        return Result.getResult().setMsg("分配角色成功").setCode(200);
    }
    @PostMapping("/selectAdminInfo")
    @ApiOperation("管理员信息查询")
    public Result<List<AdminInfoDto>> selectAdminInfo(@RequestBody SelectAdminInfoForm form) {
        System.out.println(form.getPageNum());
        System.out.println(form.getPageSize());
        int offset = (form.getPageNum()-1) *form.getPageSize();
        AllAdminInfoDto dto = adminInfoService.selectAdminInfo(BeanUtil.toBean(form, SelectAdminInfoParam.class),offset);
        return Result.getListResult(AdminInfoDto.class).setData(dto.getList()).setCode(200).setTotal(dto.getTotal());
    }
    @PostMapping("/editStationId")
    @ApiOperation("修改管理员站点")
    public Result editStationId(@RequestBody EditStationIdForm form) {
        adminInfoService.editStationId(BeanUtil.toBean(form, EditStationIdParam.class));
        return Result.getResult().setMsg("修改管理员岗位成功").setCode(200);
    }
    @GetMapping("/selectAdminById2")
    @ApiOperation("根据id查询管理员信息")
    public Result<AdminInfo> selectAdminById2(@RequestParam Integer adminId) {
        AdminInfo adminInfo=adminInfoService.selectAdminById2(adminId);
        return Result.getResult(AdminInfo.class).setData(adminInfo).setCode(200);
    }

    @PostMapping("/findByStationId")
    public Result<Page<AdminInfo>> findByStationId(@RequestBody FindSuitableRiderDTO dto){
        Page<AdminInfo> page = adminInfoService.findByStationId(dto);
        return Result.getPageResult(AdminInfo.class).setData(page).setCode(200).setMsg("查询特定条件骑手信息成功");
    }

    /**
     * 查询所有新增站点时可以当做负责人的管理员信息
     */
    @GetMapping("/selectAdmin")
    @ApiOperation("查询所有新增站点时可以当做负责人的管理员信息")
    public Result<List<AdminInfo>> selectAdmin() {
        List<AdminInfo> adminInfos=adminInfoService.selectAdmin();
        return Result.getListResult(AdminInfo.class).setData(adminInfos).setMsg("查询所有新增站点时可以当做负责人的管理员信息成功").setCode(200);
    }

    /**
     * 根据管理员名查询管理员信息
     */
    @GetMapping("/selectAdminByAdminName")
    @ApiOperation("根据管理员名查询管理员信息")
    public Result<AdminInfo> selectAdminByAdminName(@RequestParam("adminName") String adminName) {
        AdminInfo admin=adminInfoService.selectAdminByAdminName(adminName);
        return Result.getResult(AdminInfo.class).setData(admin).setMsg("根据管理员名查询管理员信息").setCode(200);
    }

    /**
     * 根据站点ID查询骑手(转移订单分配骑手)
     * */
    @GetMapping("/findByStation")
    @ApiOperation("根据站点ID查询骑手")
    public Result<List<AdminInfo>> findByStation(@RequestParam("stationId") Integer stationId) {
        List<AdminInfo> dto = adminInfoService.findByStation(stationId);
        return Result.getListResult(AdminInfo.class).setData(dto).setMsg("根据站点ID查询骑手").setCode(200);
    }

    /**
     * 查询符合条件的骑手
     * */
    @PostMapping("/findAdmin")
    @ApiOperation("查询符合条件的骑手")
    Result<List<AdminInfo>> findAdmin(@RequestBody FindAdminDTO dtos){
        List<AdminInfo> dto = adminInfoService.findAdmin(dtos);
        return Result.getListResult(AdminInfo.class).setData(dto).setMsg("根据站点ID查询骑手").setCode(200);
    }
}

